﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1RoutedEvent;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    Point _pos;
    bool _isDrawing;
    Brush _stroke = Brushes.Black;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void OnMouseDown(object sender, MouseButtonEventArgs e)
    {
        var rect = e.Source as Rectangle;
        if(rect != null)
        {
            _stroke = rect.Fill; //设置笔刷，用矩形的填充笔刷
            return;
        }
        _isDrawing = true;
        _pos = e.GetPosition(_root); //返回鼠标指针相对于指定元素的位置。
        _root.CaptureMouse(); //尝试强制将鼠标捕获到此元素。
    }

    /// <summary>
    /// 如果处于绘图模式，则创建一个Line对象，设置其两个点的位置，并将其添加到画布中。
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void OnMouseMove(object sender, MouseEventArgs e)
    {
        if (!_isDrawing) return;

        Line line = new Line();
        line.X1 = _pos.X;
        line.Y1 = _pos.Y;
        _pos = e.GetPosition(_root);
        line.X2 = _pos.X;
        line.Y2 = _pos.Y;
        line.Stroke = _stroke; //笔刷Brush，画笔/笔画Stroke，绘制Shape轮廓。
        line.StrokeThickness = 1; //Shape 轮廓的宽度。
        _root.Children.Add(line);
    }

    private void OnMouseUp(object sender, MouseButtonEventArgs e)
    {
        _isDrawing = false;
        _root.ReleaseMouseCapture(); //如果此元素持有鼠标捕获，则释放鼠标捕获。
    }
}